﻿using Hiver.Util.Config;
using Hiver.Util.Config.Model;
using CSRedis;

namespace Hiver.Util.Redis
{
    /// <summary>
    /// Redis连接类
    /// </summary>
    public class RedisConn
    {
        /// <summary>
        /// 单例模型
        /// </summary>
        public static CSRedisClient _instance = null;

        /// <summary>
        /// 获得Redis数据库连接
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static CSRedisClient GetDatabase(int i)
        {
            if (_instance == null)
            {
                ApplicationConfigModel config = YamlHelper<ApplicationConfigModel>.Load();
                if (config == null)
                    Error.Show(1);
                if (config.Redis == null)
                    Error.Show(4);
                string connectionString = config.Redis.Host + ":" + config.Redis.Port;
                if (!string.IsNullOrEmpty(config.Redis.Password))
                    connectionString += ",password=" + config.Redis.Password;
                if (config.Redis.PoolSize > 0)
                    connectionString += ",poolsize=" + config.Redis.PoolSize;
                connectionString += ",defaultDatabase=" + i;
                if (!string.IsNullOrEmpty(config.Redis.Prefix))
                    connectionString += ",prefix=" + config.Redis.Prefix;
                _instance = new CSRedisClient(connectionString);
            }
            return _instance;
        }

        /// <summary>
        /// 获得Redis哨兵模式连接
        /// </summary>
        /// <returns></returns>
        public static CSRedisClient GetRedisSentinel()
        {
            if (_instance == null)
            {
                ApplicationConfigModel config = YamlHelper<ApplicationConfigModel>.Load();
                if (config == null)
                    Error.Show(1);
                if (config.RedisSentinel == null)
                    Error.Show(4);
                string connectionString = "mymaster";
                if (!string.IsNullOrEmpty(config.RedisSentinel.Password))
                    connectionString += ",password=" + config.RedisSentinel.Password;
                if (!string.IsNullOrEmpty(config.RedisSentinel.Prefix))
                    connectionString += ",prefix=" + config.RedisSentinel.Prefix;
                _instance = new CSRedisClient(connectionString, config.RedisSentinel.Hosts.ToArray());
            }
            return _instance;
        }
    }
}